package net.sudot.chess.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 浏览器过滤器
 * <p>
 * 根据不同浏览器类型跳转到不同地址
 * <ul>
 * <li>IE浏览器(MSIE):Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)</li>
 * <li>谷歌浏览器(Chrome):Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36</li>
 * <li>火狐浏览器(Firefox):Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0</li>
 * </ul>
 *
 * @author 唐家林
 * @time 2014-06-15
 */
//@WebFilter(initParams = {
//        @WebInitParam(name = "unsupportedMatches", value = "MSIE")
//})
public class InternetExplorerFilter implements Filter {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
    protected final boolean isDebugEnabled = logger.isDebugEnabled();
    private String forward = null;
    private Pattern pattern = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String unsupportedMatches = filterConfig.getInitParameter("unsupportedMatches");
        forward = filterConfig.getInitParameter("forward");
        pattern = unsupportedMatches == null ? null : Pattern.compile(".*(?i)" + unsupportedMatches + ".*");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hsr = (HttpServletRequest) request;
        String userAgent = hsr.getHeader("User-Agent");

        if (pattern == null || !pattern.matcher(userAgent).matches() || forward.equals(hsr.getServletPath())) {
            if (isDebugEnabled) {logger.debug(">>>已放行    |浏览器标识:" + userAgent);}
            chain.doFilter(request, response);
        } else {
            if (isDebugEnabled) {logger.debug(">>>重定向    |浏览器标识:" + userAgent);}
//			((HttpServletResponse) response).sendRedirect(hsr.getContextPath() + forward);
            request.getRequestDispatcher(forward).forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
